#include "StdAfx.h"
#include "Types.h"
#include <comdef.h>
#include "../Infobus/DatabaseAdapter.h"

namespace infobus {
  namespace types {

    Message::Message() {
      memset(szSender, 0, sizeof szSender);
      memset(szMessage, 0, sizeof szMessage);
      memset(szTimestamp, 0, sizeof szTimestamp);
    }

    void Message::setDummyData() {
      memset(szSender, 0, sizeof szSender);
      memset(szMessage, 0, sizeof szMessage);

      this->id = 1;
      this->status = PENDING;
      this->subject = TRACES;

      strncpy(this->szSender, "DummySender", sizeof(this->szSender)-1);
      strncpy(this->szMessage, "test message", sizeof(this->szMessage)-1);
    }

    Message::Message(const Message * pOther)
    {
      memset(szSender, 0, sizeof szSender);
      memset(szMessage, 0, sizeof szMessage);

      this->id = pOther->id;
      this->status = pOther->status;
      this->subject = pOther->subject;

      strncpy(this->szSender, pOther->szSender, sizeof(this->szSender)-1);
      strncpy(this->szMessage, pOther->szMessage, sizeof(this->szMessage)-1);
    }

    Message::Message(long lId, E_STATUS status, E_SUBJECT subject, const char* pszSender, const char* pszMsg)
    {
      memset(szSender, 0, sizeof szSender);
      memset(szMessage, 0, sizeof szMessage);

      this->id = lId;
      this->status = status;
      this->subject = subject;

      if (pszSender)
        strncpy(this->szSender, pszSender, sizeof(this->szSender)-1);
      if (pszMsg)
        strncpy(this->szMessage, pszMsg, sizeof(this->szMessage)-1);
    }

    void Message::setMessage(const char* pszMsg)
    {
      memset(szMessage, 0, sizeof szMessage);
      if (pszMsg)
        strncpy(this->szMessage, pszMsg, sizeof(this->szMessage)-1);
    }

    void Message::setTimestamp(const char* pszTs)
    {
      memset(szTimestamp, 0, sizeof szTimestamp);
      if (pszTs)
        strncpy(this->szTimestamp, pszTs, sizeof(this->szTimestamp)-1);
    }

    std::stringstream& Message::operator<<(std::stringstream &ss)
    {
      ss << "<message>" << std::endl
         << "  <header>" << std::endl
         << "    <id>"<< _bstr_t(id) <<"</id>" << std::endl
         << "    <date>"+_bstr_t(szTimestamp)+"</date>" << std::endl
         << "    <sender>"<< szSender <<"</sender>" << std::endl
         << "    <subject>"<< _bstr_t(DatabaseAdapter::SubjectText(this->subject)) <<"</subject>" << std::endl
         << "  </header>" << std::endl
         << "  <body>" << std::endl
         << szMessage 
         << "  </body>" << std::endl
         << "</message>"
         << std::endl;

      return ss;
    }

  }
};